package com.penghaisoft.microwms.material.web.insidewarehouse.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.MediaType;

import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.penghaisoft.microwms.common.Constant;
import com.penghaisoft.microwms.common.base.model.BaseDictionary;
import com.penghaisoft.microwms.common.controller.BaseController;
import com.penghaisoft.microwms.common.data.model.RawRequisition;
import com.penghaisoft.microwms.common.dto.ConRawCondDto;
import com.penghaisoft.microwms.common.dto.MesConRawReqDto;
import com.penghaisoft.microwms.common.dto.Resp;
import com.penghaisoft.microwms.common.dto.TransResult;
import com.penghaisoft.microwms.common.dto.UserFactoryDto;
import com.penghaisoft.microwms.common.page.Pager;
import com.penghaisoft.microwms.common.service.IMesInterfaceService;
import com.penghaisoft.microwms.common.service.MesProperties;
import com.penghaisoft.microwms.common.util.ExcelExpUtil;
import com.penghaisoft.microwms.common.wms.model.RawLockLog;
import com.penghaisoft.microwms.common.wms.model.RawStorageSn;
import com.penghaisoft.microwms.material.web.insidewarehouse.service.IBaseDictionaryService;
import com.penghaisoft.microwms.material.web.insidewarehouse.service.IMaterialInsideService;

import lombok.extern.slf4j.Slf4j;


/** 
* @ClassName: InsideRawStorageSnController 
* @Description: 原材料库存明细查询
* @author jzh
* @date 2018年5月18日 上午11:10:10  
*/
@RestController
@RequestMapping(value = "insidewarehouse/RawStorageSn")
@Slf4j
public class InsideRawStorageSnController extends BaseController  {
	
	@Autowired
	private IMaterialInsideService iMaterialInsideService;
	@Autowired
	private IMesInterfaceService mesInterfaceService;
	@Resource
	private MesProperties mesProperties;
	@Autowired
	private IBaseDictionaryService baseDictionaryService;
	
	@PostMapping("list")
	public TransResult list(@RequestParam(name = "page", defaultValue = "1") int page,
                            @RequestParam(name = "rows", defaultValue = "10") int rows, RawStorageSn rawStorageSn) {
		rawStorageSn.preQuery();
		Pager<RawStorageSn> result = iMaterialInsideService.findRawStorageSnByCondition(page, rows, rawStorageSn);
		
		String sumInfo = result.getOrder();
		if (sumInfo != null && sumInfo.length() > 0) {
			result.setOrder(sumInfo);
		}
		
		return success(result);
	}
	
	/**
	 * @Title: changeList
	 * @Description: 查询原材料库存变更历史
	 * @date 2019年3月15日 上午9:24:28
	 * @author luoteng
	 * @param page
	 * @param rows
	 * @param rawStorageSn
	 * @return TransResult   
	 */
	@PostMapping("storage/change/list")
	public TransResult changeList(@RequestParam(name = "page", defaultValue = "1") int page,
                            @RequestParam(name = "rows", defaultValue = "10") int rows, RawStorageSn rawStorageSn) {
		rawStorageSn.preQuery();
		Pager<RawStorageSn> result = iMaterialInsideService.queryStorageChangeList(page, rows, rawStorageSn);
		
		return success(result);
	}
	

	/*
	 * 导出
	 */
	@GetMapping("storage/change/list/exp")
	public String changeListExp(RawStorageSn rawStorageSn, HttpServletRequest request, HttpServletResponse response){
		rawStorageSn.preQuery();
		int page = 1;
		int rows = 60000;
		Pager<RawStorageSn> result = iMaterialInsideService.queryStorageChangeList(page, rows, rawStorageSn);
		
		List<RawStorageSn> dataList= result.getRecords();
		

		List<Map> columnList = new ArrayList<Map>();
		Map<String,String> columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "合同编号");
		columnMap.put("columnBeanName", "contractNo");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "型号");
		columnMap.put("columnBeanName", "model");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "型号描述");
		columnMap.put("columnBeanName", "modelDesc");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "型号类型");
		columnMap.put("columnBeanName", "modelType");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "期初数量");
		columnMap.put("columnBeanName", "storageSAmount");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "入库数量");
		columnMap.put("columnBeanName", "inAmount");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "退入数量");
		columnMap.put("columnBeanName", "backAmount");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "出库数量");
		columnMap.put("columnBeanName", "outAmount");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "借入数量");
		columnMap.put("columnBeanName", "changeInNum");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "借出数量");
		columnMap.put("columnBeanName", "changeOutNum");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "期末数量");
		columnMap.put("columnBeanName", "storageEAmount");
		columnList.add(columnMap);
		
		SXSSFWorkbook sw = ExcelExpUtil.generateWorkbook(dataList, columnList);
		
		OutputStream out = null;
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String sdfDate = sdf.format(date);
		String fileName = "原材料库存变更历史"+sdfDate+".xlsx";// 文件名
		try {
			out = response.getOutputStream();
			response.setContentType("application/force-download");// 设置强制下载不打开
			response.setHeader("Content-Disposition","attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8"));
			sw.write(out);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		
		return "success";
	}
	
	
	/** 
	* @Title: kulingList 
	* @Description: 库龄超期预警
	* @param @param page
	* @param @param rows
	* @param @param rawStorageSn
	* @param @return  参数说明 
	* @return TransResult    返回类型
	* @author jzh 
	* @throws 
	*/
	@PostMapping("kulinglist")
	public TransResult kulingList(@RequestParam(name = "page", defaultValue = "1") int page,
                            @RequestParam(name = "rows", defaultValue = "10") int rows, RawStorageSn rawStorageSn) {
		rawStorageSn.preQuery();
		
//		if(rawStorageSn.getKulingMin()!=null&&rawStorageSn.getKulingMin().compareTo(Constant.KULING_OFF)<0){
//			rawStorageSn.setKulingMin(Constant.KULING_OFF);
//		}else if(rawStorageSn.getKuling()!=null&&rawStorageSn.getKuling().compareTo(Constant.KULING_OFF)<0){
//			return fail("查无数据");
//		}else if(rawStorageSn.getKulingMax()!=null&&rawStorageSn.getKulingMax().compareTo(Constant.KULING_OFF)<0){
//			return fail("查无数据");
//		}else if(rawStorageSn.getKulingMax()!=null&&rawStorageSn.getKulingMax().compareTo(Constant.KULING_OFF)<0){
//			rawStorageSn.setKulingMin(Constant.KULING_OFF);
//		}else{
//			rawStorageSn.setKulingMin(Constant.KULING_OFF);
//		}
		
//		rawStorageSn.setKulingConstant(Constant.KULING_OFF);
		
		List<UserFactoryDto> fcList = getUserFactories();
		if(fcList != null && !fcList.isEmpty() && fcList.get(0).getWarningDays() != null) {
			rawStorageSn.setKulingConstant(new BigDecimal(fcList.get(0).getWarningDays()));
		}else {
			TransResult result = new TransResult();
			result.setCode(Constant.FAIL);
			result.setMsg("请联系管理员，配置预警天数！");
			return result;
		}
		
		Pager<RawStorageSn> result = iMaterialInsideService.findKulingOff(page, rows, rawStorageSn);
		return success(result);
	}
	
	
	/** 
	 * @Title whiteBlackListIn
	 * @Description 查询黑白料入库明细
	 * @author luoteng
	 * @date 2018年6月4日:下午4:36:31
	 * @param page
	 * @param rows
	 * @param rawStorageSn
	 * @return TransResult
	 */
	@PostMapping("whiteBlack/list/in")
	public TransResult whiteBlackListIn(@RequestParam(name = "page", defaultValue = "1") int page,
                            @RequestParam(name = "rows", defaultValue = "10") int rows, RawStorageSn rawStorageSn) {
		rawStorageSn.preQuery();
		Pager<RawStorageSn> result = iMaterialInsideService.findRawStorageSnWhiteBlackIn(page, rows, rawStorageSn);
		
		String sumInfo = result.getOrder();
		if (sumInfo != null && sumInfo.length() > 0) {
			result.setOrder(sumInfo);
		}
		
		return success(result);
	}
	
	/** 
	 * @Title whiteBlackListOut
	 * @Description 查询黑白料出库明细
	 * @author luoteng
	 * @date 2018年6月4日:下午4:36:31
	 * @param page
	 * @param rows
	 * @param rawStorageSn
	 * @return TransResult
	 */
	@PostMapping("whiteBlack/list/out")
	public TransResult whiteBlackListOut(@RequestParam(name = "page", defaultValue = "1") int page,
                            @RequestParam(name = "rows", defaultValue = "10") int rows, RawStorageSn rawStorageSn) {
		rawStorageSn.preQuery();
		Pager<RawStorageSn> result = iMaterialInsideService.findRawStorageSnWhiteBlackOut(page, rows, rawStorageSn);
		
		String sumInfo = result.getOrder();
		if (sumInfo != null && sumInfo.length() > 0) {
			result.setOrder(sumInfo);
		}
		
		return success(result);
	}
	
	
	@GetMapping("r/detail")
	public TransResult findRawStorageSnByCode(RawStorageSn rawStorageSn) {
		rawStorageSn.preQuery();
		List<RawStorageSn> list = iMaterialInsideService.findRawStorageSnByCode(rawStorageSn);
		return success(list);
	}
	
	@PostMapping("r/detailPost")
	public TransResult postRawStorageSnByCode(RawStorageSn rawStorageSn) {
		rawStorageSn.preQuery();
		List<RawStorageSn> list = iMaterialInsideService.findRawStorageSnByCode(rawStorageSn);
		return success(list);
	}
	

	@PostMapping("uplist")
	public TransResult updateList(@RequestBody List<RawStorageSn> list) {
		TransResult reuslt = new TransResult();
		String currentUserName = getLoginName();
		RawLockLog rawLockLog = new RawLockLog();
		rawLockLog.setLockBy(currentUserName);
		Resp resp = new Resp();
		try {
		 resp = iMaterialInsideService.updateRawStorageSnStatus(list,rawLockLog);
		} catch(RuntimeException e){
			reuslt.setCode("0");
			System.out.print(e.getMessage());
			reuslt.setMsg(e.getMessage());
			return reuslt;
		}
		return fromResp(resp);
	}
	
	/** 
	 * @Title editRawStorageSnIn
	 * @Description 原材料入库明细 新增 修改
	 * @author luoteng
	 * @date 2018年6月4日:下午1:45:10
	 * @param rawStorageSn
	 * @return TransResult
	 */
	@PostMapping("in/edit")
	public TransResult editRawStorageSnIn(RawStorageSn rawStorageSn) {
		Date now = new Date();
		if(rawStorageSn.getStorageSnId() == null || "".equals(rawStorageSn.getStorageSnId())){
			rawStorageSn.setActiveFlag("1");
			rawStorageSn.setBarcodeStatus("0");
//			货主（0：本公司 1：外公司）
			rawStorageSn.setUserDefined3("0");
			rawStorageSn.setCreateBy(getLoginName());
			rawStorageSn.setGmtCreate(now);
//			'是否辅料：0 是  1 否',
			rawStorageSn.setIsAccessories("0");
			iMaterialInsideService.createRawStorageSnIn(rawStorageSn);
		}else{
			rawStorageSn.setLastModifiedBy(getLoginName());
			rawStorageSn.setGmtModified(now);
			iMaterialInsideService.updateRawStorageSn(rawStorageSn);
		}
		return success();
	}
	
	/** 
	 * @Title editRawStorageSnOut
	 * @Description 原材料出库明细 新增 修改
	 * @author luoteng
	 * @date 2018年6月4日:下午1:45:10
	 * @param rawStorageSn
	 * @return TransResult
	 */
	@PostMapping("out/edit")
	public TransResult editRawStorageSnOut(RawStorageSn rawStorageSn) {
		TransResult result = new TransResult();
		Date now = new Date();
		if(rawStorageSn.getStorageSnId() == null || "".equals(rawStorageSn.getStorageSnId())){
			rawStorageSn.setActiveFlag("1");
			rawStorageSn.setBarcodeStatus("0");
//			货主（0：本公司 1：外公司）
			rawStorageSn.setUserDefined3("0");
			rawStorageSn.setCreateBy(getLoginName());
			rawStorageSn.setGmtCreate(now);
//			'是否辅料：0 是  1 否',
			rawStorageSn.setIsAccessories("0");
			if(rawStorageSn.getAmount() != null){
				rawStorageSn.setAmount(rawStorageSn.getAmount().negate());
			}else{
				result.setCode(Constant.FAIL);
				result.setMsg("请输入出库数量！");
				return result;
			}
			Resp resp = iMaterialInsideService.createRawStorageSnOut(rawStorageSn);
			result.setCode(resp.getCode());
			result.setMsg(resp.getMsg());
			return result;
		}else{
			rawStorageSn.setLastModifiedBy(getLoginName());
			rawStorageSn.setGmtModified(now);
			if(rawStorageSn.getAmount() != null){
				rawStorageSn.setAmount(rawStorageSn.getAmount().negate());
			}
			Resp resp = iMaterialInsideService.updateRawStorageSnOut(rawStorageSn);
			result.setCode(resp.getCode());
			result.setMsg(resp.getMsg());
			return result;
		}
	}
	
	/** 
	 * @Title getRawStorageSn
	 * @Description 根据ID获取原材料入库信息
	 * @author luoteng
	 * @date 2018年6月4日:下午1:48:49
	 * @param id
	 * @return TransResult
	 */
	@GetMapping("get/{id}")
	public TransResult getRawStorageSn(@PathVariable("id")String id) {
		RawStorageSn rtnOb = new RawStorageSn();
		if(id != null && !"".equals(id)){
			RawStorageSn ob = new RawStorageSn();
			ob.setStorageSnId(Integer.parseInt(id));
			List<RawStorageSn> list = iMaterialInsideService.findRawStorageSnAbs(ob);
			if(list != null && !list.isEmpty()){
				rtnOb = list.get(0);
			}
		}
		return success(rtnOb);
	}
	
	/** 
	 * @Title deleteRawStorageSn
	 * @Description 原材料入库明细 新增 修改
	 * @author luoteng
	 * @date 2018年6月4日:下午1:45:10
	 * @param rawStorageSn
	 * @return TransResult
	 */
	@PostMapping("d")
	public TransResult deleteRawStorageSn(RawStorageSn rawStorageSn) {
		Date now = new Date();
//		有效标志 1-有效 0-无效
		rawStorageSn.setActiveFlag("0");
		rawStorageSn.setLastModifiedBy(getLoginName());
		rawStorageSn.setGmtModified(now);
		iMaterialInsideService.updateRawStorageSn(rawStorageSn);
		return success();
	}

	/**
	 * @wzhg 1865
	 * @param id
	 * @return
     */
	@GetMapping("findById/{id}")
	public TransResult findById(@PathVariable("id")String id){
		RawStorageSn rtnOb = new RawStorageSn();
		if(id != null && !"".equals(id)){
			RawStorageSn ob = new RawStorageSn();
			ob.setStorageSnId(Integer.parseInt(id));
			rtnOb = iMaterialInsideService.findById(ob);
		}
		return success(rtnOb);
	}
	
	@GetMapping("findById/new/{id}")
	public TransResult findByIdNew(@PathVariable("id")String id){
		RawStorageSn rtnOb = new RawStorageSn();
		if(id != null && !"".equals(id)){
			RawStorageSn ob = new RawStorageSn();
			ob.setStorageSnId(Integer.parseInt(id));
			rtnOb = iMaterialInsideService.findById(ob);
			
			if(rtnOb != null && rtnOb.getBarcodeStatus() != null) {
				TransResult result = new TransResult();
				if(rtnOb.getBarcodeStatus().equals("2")) {
					result.setCode(Constant.FAIL);
					result.setMsg("该条码已经出库，不能修改合同号！");
					return result;
				}else if(rtnOb.getBarcodeStatus().equals("1")) {
					result.setCode(Constant.FAIL);
					result.setMsg("该条码已经冻结，不能修改合同号！");
					return result;
				}else if(rtnOb.getBarcodeStatus().equals("3")) {
					result.setCode(Constant.FAIL);
					result.setMsg("该条码已经抽检冻结，不能修改合同号！");
					return result;
				}
			}
		}
		return success(rtnOb);
	}

	/**
	 * 根据id修改合同号(可以置为空可以修改为其他值)
	 * @wzhg 1865
	 * @update jzh
	 * @return
	 */
	@PostMapping("updateById")
	public TransResult updateById(RawStorageSn rawStorageSn){
		TransResult result = new TransResult();
		result.setCode(Constant.SUCCESS);
		Date now = new Date();
		rawStorageSn.setLastModifiedBy(getLoginName());
		rawStorageSn.setGmtModified(now);
		try{
			Resp resp = iMaterialInsideService.updateById(rawStorageSn);
			if(resp != null){
				result.setCode(resp.getCode());
				result.setMsg(resp.getMsg());
			}
		}catch(RuntimeException e){
			result.setCode(Constant.FAIL);
			result.setMsg(e.getMessage());
		}
		return result;
	}
	
	/** 
	* @Title: updateBySelect 
	* @Description: updateBySelect根据id修改
	* @author jzh 
	* @throws 
	*/
	@PostMapping("updateBySelect")
	public TransResult updateBySelect(RawStorageSn rawStorageSn){
		Date now = new Date();
		rawStorageSn.setLastModifiedBy(getLoginName());
		rawStorageSn.setGmtModified(now);
		iMaterialInsideService.updateBySelect(rawStorageSn);
		return success();
	}
	
	/** 
	* @Title: updatePE 
	* @Description: 修改pe管长度，（判断不能为小数，不能已出库） 
	* @author jzh 
	* @throws 
	*/
	@PostMapping("updatePE")
	public TransResult updatePE(RawStorageSn rawStorageSn){
		TransResult result = new TransResult();
		rawStorageSn.preQuery();
		RawStorageSn tmp = new RawStorageSn();
		tmp.setStorageSnId(rawStorageSn.getStorageSnId());
		List<RawStorageSn> list = iMaterialInsideService.findRawStorageSnByCode(tmp);
		if(list.size()!= 0){
			if(list.get(0).getBarcodeStatus().equals("2")){
				result.setCode("0");
				result.setMsg("条码已出库不能修改数量");
				return result;				
			}
			BigDecimal b = list.get(0).getAmount();
			if(new BigDecimal(b.intValue()).compareTo(b)!=0){
				
				result.setCode("0");
				result.setMsg("只能修改长度为整数PE管");
				return result;				
			}
		}else{
			result.setCode("0");
			result.setMsg("条码不存在");
			return result;	
		}
		
		Date now = new Date();
		rawStorageSn.setLastModifiedBy(getLoginName());
		rawStorageSn.setGmtModified(now);
		iMaterialInsideService.updateBySelect(rawStorageSn);
		return success();
	}
	
	
	/** 
	* @Title: contactUpdate 
	* @Description: 合同号更新
	* @param @param rawStorageSn
	* @param @return  参数说明 
	* @return TransResult    返回类型
	* @author luoteng 
	* @date 2018年8月14日 上午9:52:53 
	* @throws 
	*/
	@PostMapping("contact/update")
	public TransResult contactUpdate(RawStorageSn rawStorageSn){
		TransResult result = new TransResult();
		//将登陆人暂存在LastModifiedBy
		String LoginName = getLoginName();
		rawStorageSn.setLastModifiedBy(LoginName);
		result.setCode(Constant.SUCCESS);
		try{
			Resp resp = iMaterialInsideService.batchUpdateContact(rawStorageSn);
			if(resp != null){
				result.setCode(resp.getCode());
				result.setMsg(resp.getMsg());
			}
		}catch(RuntimeException e){
			result.setCode(Constant.FAIL);
			result.setMsg(e.getMessage());
		}
		
		return result;
	}
	
	
	/** 
	* @Title: contractRawRequirement 
	* @Description: 原材料销售报表
	* @param @param rawStorageSn
	* @param @return  参数说明 
	* @return TransResult    返回类型
	* @author jzh 
	* @throws 
	*/
	@PostMapping("contractRaw/requirement")
	public TransResult contractRawRequirement(@RequestBody RawStorageSn rawStorageSn) {
		TransResult result = new TransResult();
		//
		if(rawStorageSn.getContractNo()==null || rawStorageSn.getContractNo().equals("")){
			result.setCode(Constant.FAIL);
			result.setMsg("请输入合同号");
			return result;
		}
		
		MesConRawReqDto mesConRawRequired = new MesConRawReqDto();
		mesConRawRequired.setSalesCode(rawStorageSn.getContractNo());
		
		String url =  mesProperties.getUrl() + "/imes-provider/external/interfaces/contract/material";
		JSONObject handResp = mesInterfaceService.publicWSJson(url, MediaType.APPLICATION_JSON_TYPE, JSON.toJSONString(mesConRawRequired));
		JSONArray listjson = handResp.getJSONObject("data").getJSONArray("list");
		
		ConRawCondDto conRawCondDto = new ConRawCondDto();
		conRawCondDto.setContractNo(rawStorageSn.getContractNo());
		List<MesConRawReqDto> list = iMaterialInsideService.findconRawRequired(conRawCondDto);
		
		List<MesConRawReqDto> mesList = new ArrayList<MesConRawReqDto>();
		if(list.size()>0){
			for(int i=0; i<list.size();i++){
				MesConRawReqDto conRawRequired = new MesConRawReqDto();
				conRawRequired.setNum(i);
				conRawRequired.setContractNo(list.get(i).getContractNo());
				conRawRequired.setModel(list.get(i).getModel());
				conRawRequired.setInAmount(list.get(i).getInAmount());
				conRawRequired.setOutAmount(list.get(i).getOutAmount());
				conRawRequired.setKcAmount(list.get(i).getKcAmount());
				conRawRequired.setJcAmount(list.get(i).getJcAmount());
				conRawRequired.setJrAmount(list.get(i).getJrAmount());
				conRawRequired.setUnit(list.get(i).getUnit());
				
				for(int j=0; j<listjson.size();j++){
					JSONObject temp = listjson.getJSONObject(j);
					if(list.get(i).getModel().equals(temp.getString("materialCode"))){
						conRawRequired.setDemand(new BigDecimal (temp.getString("demand")));
//						conRawRequired.setUnit(temp.getString("measureUnit"));
						conRawRequired.setOwner(temp.getString("owner"));
						break;
					}
				}
				
				mesList.add(conRawRequired);
			}
		}
	
		return success(mesList);
	}
	
	
	/** 
	* @Title: contractRawRequirement 
	* @Description: 原材料销售报表
	* @param @param rawStorageSn
	* @param @return  参数说明 
	* @return TransResult    返回类型
	* @author jzh 
	* @throws 
	*/
	@PostMapping("contractRaw/requirement/select")
	public TransResult contractRawRequirementSelect(@RequestBody RawStorageSn rawStorageSn) {
		TransResult result = new TransResult();
		//
		MesConRawReqDto mesConRawRequired = new MesConRawReqDto();
		if(rawStorageSn.getContractNo()==null || rawStorageSn.getContractNo().equals("")){
			result.setCode(Constant.FAIL);
			result.setMsg("请输入合同号");
			return result;
		}else{
			mesConRawRequired.setSalesCode(rawStorageSn.getContractNo());
			mesConRawRequired.setModelCode(rawStorageSn.getModel());
		}
		//mesProperties.getUrl() 
		String url =  mesProperties.getUrl() + "/imes-provider/external/interfaces/contract/material";
		JSONObject handResp = mesInterfaceService.publicWSJson(url, MediaType.APPLICATION_JSON_TYPE, JSON.toJSONString(mesConRawRequired));
		//List<MesConRawReqDto> JSONArray
		JSONArray listjson = handResp.getJSONObject("data").getJSONArray("list");
		List<MesConRawReqDto> mesList = new ArrayList<MesConRawReqDto>();
		List<String> modelList = new ArrayList<String>();
		if(listjson.size()>0){
			MesConRawReqDto conRawRequired = null;
			for(int i = 0;i < listjson.size();i++){
				JSONObject temp = listjson.getJSONObject(i);
				conRawRequired = new MesConRawReqDto();
				conRawRequired.setNum(i);
				conRawRequired.setContractNo(temp.getString("salesCode"));
				conRawRequired.setMaterialCode(temp.getString("materialCode"));
				
				//查询多个型号in查询
				modelList.add(temp.getString("materialCode"));
				conRawRequired.setMaterialName(temp.getString("materialName"));
				conRawRequired.setMaterialType(temp.getString("materialType"));
				conRawRequired.setDemand(new BigDecimal (temp.getString("demand")));
				conRawRequired.setUnit(temp.getString("measureUnit"));
				conRawRequired.setOwner(temp.getString("owner"));
				mesList.add(conRawRequired);
			}
		}else{
			result.setCode(Constant.FAIL);
			result.setMsg("MES无返回数据");
			return result;
		}
		ConRawCondDto conRawCondDto = new ConRawCondDto();
		conRawCondDto.setModelList(modelList);
		//插入合同号
		conRawCondDto.setContractNo(rawStorageSn.getContractNo());
		List<MesConRawReqDto> list = iMaterialInsideService.findconRawRequired(conRawCondDto);
		if(list.size()>0){
			for(int i=0; i<list.size();i++){
				for(int j=0; j<mesList.size();j++){
					if(list.get(i).getModel().equals(mesList.get(j).getMaterialCode())){
//						list.get(i).setDemand(mesList.get(j).getDemand());
//						mesList.get(j).setUnit(list.get(i).getUnit());
						mesList.get(j).setInAmount(list.get(i).getInAmount());
						mesList.get(j).setOutAmount(list.get(i).getOutAmount());
						mesList.get(j).setKcAmount(list.get(i).getKcAmount());
						mesList.get(j).setJcAmount(list.get(i).getJcAmount());
						mesList.get(j).setJrAmount(list.get(i).getJrAmount());
					}
				}
			}
		}else{
			return success(mesList);
		}
	
		return success(mesList);
	}


	/** 
	* @Title: listExp 
	* @Description: 
	* @param @param rawStorageSn
	* @param @param request
	* @param @param response
	* @param @return  参数说明 
	* @return String    返回类型
	* @author jzh 
	* @throws 
	*/
	@GetMapping("listSnExp")
	public String listExp(RawStorageSn rawStorageSn, HttpServletRequest request, HttpServletResponse response){
		rawStorageSn.setActiveFlag("1");
		List<RawStorageSn> dataList = iMaterialInsideService.queryStorageSnExp(rawStorageSn);
		BaseDictionary baseDictionary1 = new BaseDictionary();
		baseDictionary1.setActiveFlag("1");
		baseDictionary1.setDicType("model_type");
		List<BaseDictionary> list1 = baseDictionaryService.queryAllByCondition(baseDictionary1);
		if (dataList != null && !dataList.isEmpty()) {
			for (RawStorageSn tmpData : dataList) {
				if (list1 != null && !list1.isEmpty()) {
					for (BaseDictionary tmp : list1) {
						// 判断产品类型
						if (tmp.getDicCode().equals(tmpData.getModelType())) {
							tmpData.setModelType(tmp.getDicName());
						}
						// 判断货主类型
						if ("0".equals(tmpData.getUserDefined3())) {
							tmpData.setUserDefined3("本公司");
						}
						else if ("1".equals(tmpData.getUserDefined3())) {
							tmpData.setUserDefined3("外公司");
						}
						// 判断状态
						if ("0".equals(tmpData.getBarcodeStatus())) {
							tmpData.setBarcodeStatus("可用");
						}
						else if ("1".equals(tmpData.getBarcodeStatus())) {
							tmpData.setBarcodeStatus("冻结");
						}
						else if ("2".equals(tmpData.getBarcodeStatus())) {
							tmpData.setBarcodeStatus("已出库");
						}
						else if ("3".equals(tmpData.getBarcodeStatus())) {
							tmpData.setBarcodeStatus("报废");
						}
						// 判断冻结原因
						if ("2".equals(tmpData.getLockReason())){
							tmpData.setLockReason("质量冻结");
						}
						else if ("4".equals(tmpData.getLockReason())){
							tmpData.setLockReason("手工冻结");
						}
						
						
					}
				}
			}
		}
		
		List<Map> columnList = new ArrayList<Map>();
		Map<String,String> columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "合同编号");
		columnMap.put("columnBeanName", "contractNo");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "条码");
		columnMap.put("columnBeanName", "barcode");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "型号");
		columnMap.put("columnBeanName", "model");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "型号描述");
		columnMap.put("columnBeanName", "modelDesc");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "型号类型");
		columnMap.put("columnBeanName", "modelType");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "货主");
		columnMap.put("columnBeanName", "userDefined3");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "供应商");
		columnMap.put("columnBeanName", "userDefined2");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "单位");
		columnMap.put("columnBeanName", "unit");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "长度");
		columnMap.put("columnBeanName", "amount");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "状态");
		columnMap.put("columnBeanName", "barcodeStatus");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "库龄 ");
		columnMap.put("columnBeanName", "kuling");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "库位 ");
		columnMap.put("columnBeanName", "wlCode");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "冻结原因");
		columnMap.put("columnBeanName", "lockReason");
		columnList.add(columnMap);
		
		SXSSFWorkbook sw = ExcelExpUtil.generateWorkbook(dataList, columnList);
		
		OutputStream out = null;
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String sdfDate = sdf.format(date);
		String fileName = "原材料库存明细"+sdfDate+".xlsx";// 文件名
		try {
			out = response.getOutputStream();
			response.setContentType("application/force-download");// 设置强制下载不打开
			response.setHeader("Content-Disposition","attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8"));
			sw.write(out);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	return "sucess";
	}

	/** 
	 * @Title queryContract
	 * @Description 获取领料单号（生产任务号）
	 * @author luoteng
	 * @date 2018年5月28日:上午10:08:45
	 * @param dicType
	 * @return TransResult
	 */
	@GetMapping("get/rawRequisitionNo")
	public TransResult queryContract(RawRequisition rawRequisition) {
		List<RawRequisition> list = iMaterialInsideService.queryRawRequisitionNo(rawRequisition);
		return success(list);
	}
}
